package visam.core;

public class Array
{
    private char[] array;
    private int    size;
    
    Array(int initialCapacity)
    {
        array = new char[initialCapacity];
        size = 0;
    }
    
    public int getSize()
    {
        return size;
    }
    
    public void set(int index, char c)
    {
        if (index > size) throw new IndexOutOfBoundsException();
        array[index] = c;
    }
    
    public char get(int pos)
    {
        return array[pos];
    }
    
    public char[] getArray()
    {
        char[] rc = new char[size];
        System.arraycopy(array, 0, rc, 0, size);
        return rc;
    }
    
    public void prepend(char c)
    {
        if (array.length == size)
        {
            char[] tmp = new char[array.length];
            System.arraycopy(array, 0, tmp, 0, array.length);
            array = new char[array.length * 2];
            System.arraycopy(tmp, 0, array, 0, tmp.length);
        }
        System.arraycopy(array, 0, array, 1, size);
        array[0] = c;
        size += 1;
    }
    
    public void prepend(char[] cc)
    {
        if (array.length + cc.length >= size)
        {
            char[] tmp = new char[array.length];
            System.arraycopy(array, 0, tmp, 0, array.length);
            array = new char[array.length + cc.length > size ? cc.length : array.length];
            System.arraycopy(tmp, 0, array, cc.length, tmp.length);
        }
        System.arraycopy(cc, 0, array, 0, cc.length);
    }
    
    public void delete(int no)
    {
        if (size - no >= 0)
            size -= no;
        else
            size = 0;
    }
    
    public void append(char c)
    {
        if (array.length == size)
        {
            char[] tmp = new char[array.length];
            System.arraycopy(array, 0, tmp, 0, array.length);
            array = new char[array.length + 40];
            System.arraycopy(tmp, 0, array, 0, tmp.length);
        }
        array[size++] = c;
    }
    
    public void append(char[] cc)
    {
        if (array.length <= size + cc.length)
        {
            char[] tmp = new char[array.length];
            System.arraycopy(array, 0, tmp, 0, array.length);
            array = new char[array.length * 2 + cc.length];
            System.arraycopy(tmp, 0, array, 0, tmp.length);
        }
        System.arraycopy(cc, 0, array, size, cc.length);
        size += cc.length;
    }
    
    public void dump()
    {
        String tmp = new String(array, 0, size);
        System.out.println("[" + tmp + "] size: " + size);
    }
    
    public void set(char[] input)
    {
        if (input != null)
        {
            if (input.length > size) array = new char[input.length];
            System.arraycopy(input, 0, array, 0, input.length);
            size = input.length;
        }
    }
    
}
